package cn.base.web.auth.inner.config;

import cn.base.web.auth.inner.realm.InnerAuthenRealm;
import cn.base.web.auth.inner.token.InnerAuthenTokenCreator;
import cn.base.web.authc.AccessControl;
import cn.rengy.auth.Authentication;
import cn.rengy.auth.AuthenToken;
import cn.rengy.auth.entity.ResponseEntity;
import cn.rengy.auth.exception.AuthException;
import cn.rengy.lang.DataConverter;
import cn.rengy.lang.ResultEntity;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;



/**
 * 微服务内部访问控制
 * 不做uir权限判断(在gateway判断)，只验证jwt
 */
@ConditionalOnProperty(name = "enable.cn.base.web.auth.inner.config.InnerAccessControl", havingValue = "true",matchIfMissing=false)
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class InnerAccessControl implements AccessControl {

	@Autowired
	private DataConverter dataConverter;

	@Autowired
	private InnerAuthenRealm innerAuthenRealm;

	@Autowired
	private InnerAuthenTokenCreator innerAuthenTokenCreator;
	@Override
	public ResultEntity<HttpStatus, Authentication> isAccessAllowed(Object _request, Object _response) {
		HttpServletRequest request=(HttpServletRequest)_request;
		//HttpServletResponse response=(HttpServletResponse)_response;
		String method=request.getMethod();
		//忽略OPTIONS请求
		if(method.equals(RequestMethod.OPTIONS.name())) {
			return ResultEntity.ok(HttpStatus.OK,null);
		}
		/**
		 * 参考ResourceHttpRequestHandler.handleRequest
		 * if (HttpMethod.OPTIONS.matches(request.getMethod())) {
		 * 			response.setHeader(HttpHeaders.ALLOW, getAllowHeader());
		 * 			return;
		 * 		        }
		 * **/
		ResultEntity<HttpStatus, ResponseEntity> resultEntity=ResultEntity.ok();
		//long startTime = System.nanoTime();
		//boolean isAllow=false;//是否允许访问
		//String msg="fail";
		//int responseStatus=HttpStatus.UNAUTHORIZED.value();

		try {
			AuthenToken authenticationToken=innerAuthenTokenCreator.getAuthenticationToken(request);
			Authentication info = innerAuthenRealm.getAuthenticationInfo(authenticationToken);
			//isAllow= true;
			return ResultEntity.ok(HttpStatus.OK,info);
		}catch(AuthException e) {
			return ResultEntity.fail(HttpStatus.UNAUTHORIZED,e.getMessage());
			//String body= dataConverter.beanToJson(ResultEntity.fail(msg));
			//ResponseEntity rsp=new ResponseEntity(responseStatus,body);
			//ServletUtil.responseJson(str, response);
			//resultEntity.setData(rsp);
		}

    }



}
